//
//  SupplyAndDemandDetailsVC.m
//  phmall
//
//  Created by admin on 2017/12/20.
//  Copyright © 2017年 admin. All rights reserved.
//

#import "SupplyAndDemandDetailsVC.h"
#import "SupplyAndDemandDetailsView.h"
#import "InformationView.h"
#import "LeaveWordView.h"
#import "SupplyAndDemandDetailsModel.h"
@interface SupplyAndDemandDetailsVC ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>{
    UIView *headerView;
    SupplyAndDemandDetailsView *detailsView;
    InformationView *information;
    LeaveWordView *leaveWord;
}
@property(nonatomic,strong)MBProgressHUD *hud;
@property(strong,nonatomic)UITableView *myTableview;
@property(strong,nonatomic)SupplyAndDemandDetailsModel *model;
@end

@implementation SupplyAndDemandDetailsVC
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if ([self.type  isEqualToString:@"suppy"]) {
        [self loadDataWithSupply_detail];
    }else{
        [self loadDataWithBuy_detail];
    }
}
- (void)loadDataWithSupplySubmit{
    if (leaveWord.name.text.length==0||leaveWord.name.text==nil) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提交错误" message:@"姓名不可为空,请填写完整" preferredStyle:UIAlertControllerStyleAlert];
        [self.navigationController presentViewController:alertController animated:YES completion:nil];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"点击取消");
        }]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"点击确认");
        }]];
        return;
    }
    if (leaveWord.phone.text.length==0||leaveWord.phone.text==nil) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提交错误" message:@"联系方式不可为空,请填写完整" preferredStyle:UIAlertControllerStyleActionSheet];
        [self.navigationController presentViewController:alertController animated:YES completion:nil];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"点击取消");
        }]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"点击确认");
        }]];
        return;
    }
    if (leaveWord.adderss.text.length==0||leaveWord.adderss.text==nil) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提交错误" message:@"联系地址不可为空,请填写完整" preferredStyle:UIAlertControllerStyleActionSheet];
        [self.navigationController presentViewController:alertController animated:YES completion:nil];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"点击取消");
        }]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"点击确认");
        }]];
        return;
    }
    if (leaveWord.message.text.length==0||leaveWord.message.text==nil) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提交错误" message:@"留言内容不可为空,请填写完整" preferredStyle:UIAlertControllerStyleActionSheet];
        [self.navigationController presentViewController:alertController animated:YES completion:nil];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"点击取消");
        }]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"点击确认");
        }]];
        return;
    }
    NSString *urlstr;
    if ([self.type isEqualToString:@"suppy"]) {
        urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"supply_detail/submit"];
    }else{
        urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"buy_detail/submit"];
    }
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    [parametersDic setObject:leaveWord.name.text forKey:@"name"];
    [parametersDic setObject:leaveWord.phone.text forKey:@"tel"];
    [parametersDic setObject:leaveWord.adderss.text forKey:@"address"];
    [parametersDic setObject:leaveWord.message.text forKey:@"msg"];
    [parametersDic setObject:self.model.uid forKey:@"supply_uid"];
    [parametersDic setObject:self.model.m_uid forKey:@"supply_m_uid"];
    
    [httpTool ZBPostNetDataWith:urlstr withDic:parametersDic andSuccess:^(id responseObject) {
        NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([responseDict[@"ret"] isEqualToString:@"200"]) {
          
        }else{
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提交错误" message:@"当前用户未登录" preferredStyle:UIAlertControllerStyleAlert];
            [self.navigationController presentViewController:alertController animated:YES completion:nil];
            [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"点击取消");
            }]];
            [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"点击确认");
            }]];
        }
    } andFailure:^{
        [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2 ];
//        [SVProgressHUD showErrorWithStatus:@"网络错误"];
    }];
}
- (void)loadDataWithBuy_detail{
    
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"buy_detail"];
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    [parametersDic setObject:self.uid forKey:@"uid"];
    
    [httpTool ZBPostNetDataWith:urlstr withDic:parametersDic andSuccess:^(id responseObject) {
        NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([responseDict[@"ret"] isEqualToString:@"200"]) {
            if (responseDict[@"data"] !=[NSNull alloc]) {
                self.model = [SupplyAndDemandDetailsModel yy_modelWithDictionary:responseDict[@"data"][0]];
                detailsView.model=self.model;
                //                information.imageArray=@[@"1",@"2",@"3"].copy;
                information.model=self.model;
            }
            //添加webview前计算一次高度
            CGFloat height = [headerView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
            CGRect frame = headerView.bounds;
            frame.size.height = height;
            headerView.frame = frame;
            [self.myTableview setTableHeaderView:headerView];
            [headerView layoutIfNeeded];
        }
    } andFailure:^{
        if (self.emptyType==EmptyDataSetNoNetwork) {
            [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2 ];
        }
       
        self.emptyType=EmptyDataSetNoNetwork;
        [self.myTableview reloadData];
    }];
}
- (void)loadDataWithSupply_detail{

    
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"supply_detail"];
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    [parametersDic setObject:self.uid forKey:@"uid"];
    
    [httpTool ZBPostNetDataWith:urlstr withDic:parametersDic andSuccess:^(id responseObject) {
        NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([responseDict[@"ret"] isEqualToString:@"200"]) {
            if (responseDict[@"data"] !=[NSNull alloc]) {
                self.model = [SupplyAndDemandDetailsModel yy_modelWithDictionary:responseDict[@"data"][0]];
                detailsView.model=self.model;
//                information.imageArray=@[@"1",@"2",@"3"].copy;
                information.model=self.model;
            }
            //添加webview前计算一次高度
            CGFloat height = [headerView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
            CGRect frame = headerView.bounds;
            frame.size.height = height;
            headerView.frame = frame;
            [self.myTableview setTableHeaderView:headerView];
            [headerView layoutIfNeeded];
        }
        [self.hud hideAnimated:YES];
    } andFailure:^{
        [self.hud hideAnimated:YES];
//        [SVProgressHUD showErrorWithStatus:@"网络错误"];
        if (self.emptyType==EmptyDataSetNoNetwork) {
            [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2 ];
        }
        self.emptyType=EmptyDataSetNoNetwork;
        [self.myTableview reloadData];
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=Localized(@"详情");
    UIBarButtonItem* leftBar=[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"返回"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(leftBarAction)];
    self.navigationItem.leftBarButtonItem=leftBar;
    
    self.emptyType=EmptyDataSetNone;
    self.view.backgroundColor=[UIColor groupTableViewBackgroundColor];
    [self.view addSubview:self.myTableview];
    [self.myTableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(0);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view).with.offset(-self.tabBar_height-49);
    }];
    
    //整体界面
    headerView=[UIView new];
    headerView.backgroundColor=[UIColor groupTableViewBackgroundColor];
    //轮播图
    
    detailsView=[[SupplyAndDemandDetailsView alloc]init];
 
    [headerView addSubview:detailsView];
    [detailsView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.offset(0);
        //        make.height.offset(70+SCREEN_WIDTH);
        make.bottom.equalTo(detailsView.intro.mas_bottom).offset(10);
//        make.bottom.equalTo(headerView.mas_bottom).with.offset(-10).priorityHigh();
    }];
    [detailsView layoutIfNeeded];
    
    information=[[InformationView alloc]init];
    [headerView addSubview:information];
    [information mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.equalTo(detailsView.mas_bottom).offset(10);
        //        make.height.offset(70+SCREEN_WIDTH);
        make.bottom.equalTo(information.imageView.mas_bottom).offset(10);
//        make.bottom.equalTo(headerView.mas_bottom).with.offset(-10).priorityHigh();
    }];
    [information layoutIfNeeded];
    
    leaveWord=[[LeaveWordView alloc]init];
    [headerView addSubview:leaveWord];
    [leaveWord mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.equalTo(information.mas_bottom).offset(10);
        //        make.height.offset(70+SCREEN_WIDTH);
        make.bottom.equalTo(leaveWord.messageView.mas_bottom).offset(5);
//        make.bottom.equalTo(headerView.mas_bottom).with.offset(-10).priorityHigh();
    }];
    [leaveWord layoutIfNeeded];
    
    UIButton *submit=[UIButton buttonWithType:UIButtonTypeCustom];
    [submit setTitle:Localized(@"提交") forState:UIControlStateNormal];
    ViewBorderRadius(submit, 5, 0, [UIColor clearColor]);
    submit.titleLabel.font=[UIFont systemFontOfSize:15];
    [submit setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    submit.backgroundColor=[UIColor orangeColor];
    [headerView addSubview:submit];
    [submit addTarget:self action:@selector(loadDataWithSupplySubmit) forControlEvents:UIControlEventTouchUpInside];
    [submit mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(leaveWord.mas_bottom).offset(10);
        make.left.offset(10);
        make.width.offset(SCREEN_WIDTH-20);
        make.height.offset(44);
        make.bottom.equalTo(headerView.mas_bottom).with.offset(-10).priorityHigh();
    }];

    UIButton *phone=[UIButton buttonWithType:UIButtonTypeCustom];
    [phone setTitle:Localized(@"手机联系") forState:UIControlStateNormal];
    phone.titleLabel.font=[UIFont systemFontOfSize:15];
    ViewBorderRadius(phone, 0, 0.5, [UIColor groupTableViewBackgroundColor]);
    [phone setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    phone.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:phone];
    [phone mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(0);
        make.width.offset(SCREEN_WIDTH/2);
        make.height.offset(49);
        make.bottom.offset(-self.tabBar_height);
    }];

    UIButton *chat=[UIButton buttonWithType:UIButtonTypeCustom];
    [chat setTitle:Localized(@"在线联系") forState:UIControlStateNormal];
    chat.titleLabel.font=[UIFont systemFontOfSize:15];
    ViewBorderRadius(chat, 0, 0.5, [UIColor groupTableViewBackgroundColor]);
    [chat setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    chat.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:chat];
    [chat mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(0);
        make.width.offset(SCREEN_WIDTH/2);
        make.height.offset(49);
        make.bottom.offset(-self.tabBar_height);
    }];
    
    // Do any additional setup after loading the view.
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 0;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 0;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    //总高度
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *ID = @"newCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;;
    }
    cell.opaque=YES;
    cell.layer.drawsAsynchronously=YES;
    cell.layer.rasterizationScale=[UIScreen mainScreen].scale;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    //分割线补全
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}
#pragma mark  DZNEmptyDataSetDelegate
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    if(self.emptyType==EmptyDataSetNoNetwork){
        return [UIImage imageNamed:@"断网"];
    }
    return nil;
}
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView{
    if(self.emptyType==EmptyDataSetNoNetwork){
        return NO;
    }
    return YES;
}
- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
    return 0;
}
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSMutableAttributedString *currentPriceStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n%@",Localized(@"您的网络不给力啊!"),Localized(@"请您检查是否联网。")]];
    [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:22],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#E6963F"]} range:NSMakeRange(0, [Localized(@"您的网络不给力啊!") length])];
    [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:18],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#C2AA93"]} range:NSMakeRange([Localized(@"您的网络不给力啊!") length], [Localized(@"请您检查是否联网。") length])];
    
    if(self.emptyType==EmptyDataSetNoNetwork){
        return currentPriceStr;
    }
    return nil;
}
- (NSAttributedString *)buttonTitleForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state {
    NSMutableAttributedString *currentPriceStr = [[NSMutableAttributedString alloc] initWithString:Localized(@"重新加载")];
    [currentPriceStr addAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Georgia-Bold" size:18],NSForegroundColorAttributeName:[UIColor whiteColor]} range:NSMakeRange(0, [Localized(@"重新加载") length])];
    
    if(self.emptyType==EmptyDataSetNoNetwork){
        return currentPriceStr;
    }
    return nil;
}

#pragma mark - DZNEmptyDataSetDelegate

- (void)emptyDataSet:(UIScrollView *)scrollView didTapButton:(UIButton *)button {
    [self loadDataWithBuy_detail];
    self.hud=[MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow  animated:YES];
    self.hud.detailsLabel.text = Localized(@"加载中...");
}
- (void)emptyDataSetWillAppear:(UIScrollView *)scrollView {
    self.myTableview.contentOffset = CGPointZero;
}
//MARK:-GETTER
- (UITableView *)myTableview{
    if (!_myTableview) {
        _myTableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _myTableview.delegate = self;
        _myTableview.dataSource = self;
        _myTableview.backgroundColor=[UIColor groupTableViewBackgroundColor];
        _myTableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _myTableview.showsVerticalScrollIndicator=NO;
        _myTableview.scrollEnabled = YES;
        _myTableview.emptyDataSetSource=self;
        _myTableview.emptyDataSetDelegate=self;
    }
    return _myTableview;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
